package com.xn.app.muying.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.xn.app.muying.MuYingApplication;
import com.xn.app.muying.R;
import com.xn.app.muying.adpter.MineYiYuanAdapter;
import com.xn.app.muying.bean.MineYiYuanBean;
import com.xn.app.muying.util.APIMethod;
import com.xn.app.muying.util.Constants;
import com.xn.app.muying.util.HttpUtil;
import com.xn.app.muying.util.ToastUtil;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;

import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;

/**
 * Created by Administrator on 2016/10/19.
 */
public class JiuZhenActivity extends AppCompatActivity implements HttpUtil.OnGetDataListener, AdapterView.OnItemClickListener {
    private Handler handler = new Handler();
    private ListView lv;
    private MineYiYuanAdapter adapter;
    ArrayList<MineYiYuanBean> list;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_jiuzhen);
        lv = (ListView) findViewById(R.id.jiuzhen_activity_lv);
        HttpUtil.getData(APIMethod.Mine_JiuZhenYiYuan, handler, this);
        adapter = new MineYiYuanAdapter(this);
        lv.setAdapter(adapter);
        lv.setOnItemClickListener(this);

    }

    @Override
    public void onJsonData(String data) {
        try {
            JSONObject jsonObject = new JSONObject(data);
            JSONArray items = jsonObject.getJSONArray("items");
            list = new ArrayList<>();
            for (int i = 0; i < items.length(); i++) {
                JSONObject object = items.getJSONObject(i);
                String name = object.optString("name");
                int id = object.optInt("id");
                MineYiYuanBean bean = new MineYiYuanBean();
                bean.setName(name);
                bean.setId(id);
                list.add(bean);
            }
            adapter.getData(list);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

        String sign = getIntent().getStringExtra("SIGN");
        String pageIntent = getIntent().getStringExtra("PAGE_INTENT");
        Intent intent = new Intent();
        intent.putExtra("HOSPTIALNAME", list.get(i).getName());
        intent.putExtra("HOSPTIALID", list.get(i).getId());
        if (sign != null) {
            if (sign.equals("continue")) {
                if (pageIntent != null) {
                    intent.putExtra("PAGE_INTENT", pageIntent);
                    intent.setClass(this, YunChanSheZhiActivity.class);
                    startActivity(intent);
                    finish();
                } else {
                    Toast.makeText(this, "没有拿到PAGE_INTENT的值", Toast.LENGTH_SHORT).show();
                }
            } else {
                updateInterfaceData(list.get(i).getId());
//                setResult(MineFragment.FORRESULT, intent);
            }

        } else {
            Toast.makeText(this, "没有拿到SIGN的值", Toast.LENGTH_SHORT).show();
        }
    }


    private void updateInterfaceData(final int id) {
        new Thread(new Runnable() {
//            String yonghu = null;

            @Override
            public void run() {
                try {
                    HashMap<String, Integer> param = new HashMap<>();
                    param.put("antenatalCareHospitalId", id);
                    String p = new Gson().toJson(param);
                    Log.i("allen", p);

                    String tokens = Constants.getStringByName(JiuZhenActivity.this, "yonghu");
                    Type type1 = new TypeToken<HashMap<String, String>>() {
                    }.getType();
                    HashMap<String, String> token = new Gson().fromJson(tokens, type1);
                    Log.i("asdf", "access_token==" + "Bearer " + token.get("access_token"));
                    RequestBody formBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), p);
                    Request request = new Request.Builder().url("http://apitest.beierbaby.com/api/account/userinfo/antenatalcare-hospital").addHeader("Authorization", "Bearer " + token.get("access_token")).put(formBody).build();
                    okhttp3.Response response = MuYingApplication.mOkHttpClient.newCall(request).execute();
                    int code = response.code();
                    if (code == 204 || code == 200) {
                        Message msg2 = new Message();
                        msg2.what = 0;
                        msg2.obj = "";
                        handler1.sendMessage(msg2);
                    } else {
                        Message msg1 = new Message();
                        msg1.what = 1;
                        msg1.arg1 = code;
                        msg1.obj = "";
                        handler1.sendMessage(msg1);
                    }


                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    Handler handler1 = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    ToastUtil.showToast(JiuZhenActivity.this, "修改成功");
                    //将获取到的用户信息存储到SharedPreferences中
                    Constants.setStringByName(JiuZhenActivity.this, "minemessage", msg.obj.toString());
                    finish();
                    break;
                case 1:
                    ToastUtil.showToast(JiuZhenActivity.this, "修改失败");
                    finish();
                    break;
            }
        }
    };

}
